<template>
  <div class="entrust-publish">
    <GradientCard type="primary" class="publish-card">
      <template #default>
        <div class="publish-header">
          <div class="header-content">
            <el-icon class="header-icon"><Plus /></el-icon>
            <h2 class="header-title">✨ 发布委托 2.0</h2>
            <p class="header-subtitle">让校园生活更便捷，让互助更有温度</p>
          </div>
        </div>
        
        <div class="publish-content">
      
      <el-form 
        ref="formRef"
        :model="publishForm"
        :rules="rules"
        label-width="100px"
        class="publish-form"
      >
        <el-form-item label="🔍 标题" prop="title">
          <el-input 
            v-model="publishForm.title"
            placeholder="请输入委托标题"
            maxlength="50"
            show-word-limit
            class="enhanced-input"
          />
        </el-form-item>
        
        <el-form-item label="🏷️ 分类" prop="category">
          <div class="category-selector">
            <div 
              v-for="category in categories" 
              :key="category.value"
              class="category-option"
              :class="{ active: publishForm.category === category.value }"
              @click="publishForm.category = category.value"
            >
              <span class="category-icon">{{ category.icon }}</span>
              <span class="category-label">{{ category.label }}</span>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="💰 报酬" prop="reward">
          <div class="reward-input-container">
            <el-input-number
              v-model="publishForm.reward"
              :min="1"
              :max="1000"
              :precision="0"
              class="reward-input"
              placeholder="建议区间 ¥5-¥20"
            >
              <template #prefix>¥</template>
            </el-input-number>
            <div class="reward-suggestions">
              <span 
                v-for="suggestion in rewardSuggestions" 
                :key="suggestion"
                class="reward-suggestion"
                @click="publishForm.reward = suggestion"
              >
                ¥{{ suggestion }}
              </span>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="⏰ 截止" prop="deadline">
          <div class="deadline-container">
            <el-date-picker
              v-model="publishForm.deadline"
              type="datetime"
              placeholder="今天 18:00"
              class="deadline-picker"
              :disabled-date="disabledDate"
              :disabled-time="disabledTime"
            />
            <el-button 
              type="primary" 
              size="small" 
              class="reminder-btn"
              @click="showReminderSettings = true"
            >
              ＋提醒设置
            </el-button>
          </div>
        </el-form-item>
        
        <el-form-item label="📝 委托详情" prop="description">
          <div class="description-container">
            <el-input
              v-model="publishForm.description"
              type="textarea"
              :rows="4"
              placeholder="开始输入..."
              maxlength="500"
              show-word-limit
              class="description-input"
            />
            <div class="description-tools">
              <EmojiPicker @select="insertEmoji" />
              <el-button 
                type="primary" 
                size="small" 
                class="upload-btn"
                @click="triggerImageUpload"
              >
                图片上传＋
              </el-button>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="上传图片">
          <el-upload
            ref="uploadRef"
            :file-list="fileList"
            :auto-upload="false"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :before-upload="beforeUpload"
            list-type="picture-card"
            :limit="3"
            accept="image/*"
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">
                最多上传3张图片，每张不超过5MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="📱 联系方式" prop="contactType">
          <div class="contact-container">
            <div class="contact-info">
              <el-icon class="contact-icon"><ChatDotRound /></el-icon>
              <span class="contact-text">自动同步微信</span>
            </div>
            <el-button 
              type="primary" 
              size="small" 
              class="change-contact-btn"
            >
              更换 ▼
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="联系方式" prop="contactType">
          <el-radio-group v-model="publishForm.contactType">
            <el-radio label="站内信">站内信</el-radio>
            <el-radio label="手机">手机</el-radio>
            <el-radio label="微信">微信</el-radio>
            <el-radio label="QQ">QQ</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item 
          v-if="publishForm.contactType !== '站内信'" 
          :label="contactLabel" 
          prop="contactInfo"
        >
          <el-input 
            v-model="publishForm.contactInfo"
            :placeholder="`请输入${contactLabel}`"
          />
        </el-form-item>
        
        <el-form-item class="action-buttons">
          <AnimatedButton 
            type="primary" 
            size="large" 
            icon="Upload"
            :loading="submitting"
            @click="handleSubmit"
          >
            发布
          </AnimatedButton>
          <AnimatedButton 
            type="info" 
            size="large" 
            icon="Document"
            @click="handleSaveDraft"
          >
            存草稿
          </AnimatedButton>
        </el-form-item>
        
        <div class="publish-tips">
          <el-icon class="tips-icon"><Light /></el-icon>
          <span class="tips-text">💡 小贴士：详细描述可获得30%更快响应！</span>
        </div>
      </div>
    </GradientCard>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Light } from '@element-plus/icons-vue'
import GradientCard from './components/GradientCard.vue'
import AnimatedButton from './components/AnimatedButton.vue'
import EmojiPicker from './components/EmojiPicker.vue'

/**
 * 委托发布页面组件
 * @description 用于用户发布新的校园委托
 */
const router = useRouter()
const formRef = ref(null)
const uploadRef = ref(null)
const loading = ref(false)
const submitting = ref(false)
const fileList = ref([])
const showReminderSettings = ref(false)

// 分类数据
const categories = [
  { label: '外卖', value: '外卖', icon: '🍔' },
  { label: '快递', value: '快递', icon: '📦' },
  { label: '打印', value: '打印', icon: '🖨️' },
  { label: '其他', value: '其他', icon: '⋯' }
]

// 报酬建议
const rewardSuggestions = [5, 8, 10, 15, 20]

// 发布表单数据
const publishForm = reactive({
  title: '',
  category: '',
  reward: null,
  deadline: '',
  description: '',
  contactType: '站内信',
  contactInfo: ''
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入委托标题', trigger: 'blur' },
    { min: 5, max: 50, message: '标题长度在5到50个字符之间', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择委托类别', trigger: 'change' }
  ],
  reward: [
    { required: true, message: '请输入报酬金额', trigger: 'blur' },
    { type: 'number', min: 1, message: '报酬金额必须大于0', trigger: 'blur' }
  ],
  deadline: [
    { required: true, message: '请选择截止时间', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入委托详情', trigger: 'blur' },
    { min: 10, max: 500, message: '详情长度在10到500个字符之间', trigger: 'blur' }
  ],
  contactInfo: [
    { 
      required: true, 
      message: '请输入联系方式', 
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (publishForm.contactType !== '站内信' && !value) {
          callback(new Error('请输入联系方式'))
        } else {
          callback()
        }
      }
    }
  ]
}

// 计算联系方式标签
const contactLabel = computed(() => {
  const labelMap = {
    '手机': '手机号码',
    '微信': '微信号',
    'QQ': 'QQ号码'
  }
  return labelMap[publishForm.contactType] || '联系方式'
})

/**
 * 禁用过去的日期
 * @param {Date} time - 日期对象
 * @returns {boolean} 是否禁用
 */
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7 // 禁用今天之前的日期
}

/**
 * 禁用过去的时间
 * @param {Date} date - 日期对象
 * @returns {Object} 禁用的小时、分钟、秒
 */
const disabledTime = (date) => {
  if (date && date.getDate() === new Date().getDate()) {
    const hours = new Date().getHours()
    const minutes = new Date().getMinutes()
    return {
      disabledHours: () => Array.from({ length: hours }, (_, i) => i),
      disabledMinutes: (hour) => hour === hours ? Array.from({ length: minutes }, (_, i) => i) : [],
      disabledSeconds: () => []
    }
  }
  return {}
}

/**
 * 处理文件变化
 * @param {Object} file - 文件对象
 * @param {Array} fileList - 文件列表
 */
const handleFileChange = (file, fileList) => {
  console.log('文件变化：', file.name)
}

/**
 * 处理文件移除
 * @param {Object} file - 文件对象
 * @param {Array} fileList - 文件列表
 */
const handleFileRemove = (file, fileList) => {
  console.log('移除文件：', file.name)
}

/**
 * 上传前验证
 * @param {Object} file - 文件对象
 * @returns {boolean|Promise} 验证结果
 */
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件！')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB！')
    return false
  }
  return true
}

/**
 * 插入表情包
 * @param {string} emoji - 表情包
 */
const insertEmoji = (emoji) => {
  publishForm.description += emoji
}

/**
 * 触发图片上传
 */
const triggerImageUpload = () => {
  uploadRef.value?.$el.querySelector('input[type="file"]')?.click()
}

/**
 * 处理发布委托
 */
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    // 构建发布数据
    const publishData = {
      ...publishForm,
      images: fileList.value.map(file => file.url || file.raw),
      createTime: new Date().toISOString()
    }
    
    console.log('发布委托数据：', publishData)
    
    // TODO: 调用API发布委托
    // const res = await publishEntrust(publishData)
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('✨ 委托发布成功！')
    router.push('/campus-entrust/list')
    
  } catch (error) {
    console.error('发布失败：', error)
    ElMessage.error('发布失败，请检查表单信息')
  } finally {
    submitting.value = false
  }
}

/**
 * 保存草稿
 */
const handleSaveDraft = () => {
  // 保存到本地存储
  localStorage.setItem('entrustDraft', JSON.stringify(publishForm))
  ElMessage.success('草稿已保存')
}

/**
 * 取消发布
 */
const handleCancel = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要取消发布吗？已填写的内容将丢失',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '继续编辑',
        type: 'warning'
      }
    )
    router.go(-1)
  } catch {
    // 用户选择继续编辑
  }
}
</script>

<style scoped>
.entrust-publish {
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
}

.publish-card {
  max-width: 800px;
  margin: 0 auto;
}

.publish-header {
  text-align: center;
  margin-bottom: 30px;
  color: white;
}

.header-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.header-icon {
  font-size: 32px;
  margin-bottom: 8px;
}

.header-title {
  font-size: 28px;
  font-weight: 700;
  margin: 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.header-subtitle {
  font-size: 16px;
  opacity: 0.9;
  margin: 0;
}

.publish-content {
  background: white;
  border-radius: 16px;
  padding: 30px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.publish-form {
  margin-top: 20px;
}

/* 分类选择器 */
.category-selector {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 12px;
}

.category-option {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 16px 12px;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
  background: #f8f9fa;
}

.category-option:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.category-option.active {
  border-color: #667eea;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.category-icon {
  font-size: 24px;
}

.category-label {
  font-size: 14px;
  font-weight: 500;
}

/* 报酬输入 */
.reward-input-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.reward-input {
  width: 100%;
}

.reward-suggestions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.reward-suggestion {
  padding: 6px 12px;
  background: #f0f2f5;
  border-radius: 16px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.reward-suggestion:hover {
  background: #667eea;
  color: white;
  transform: scale(1.05);
}

/* 截止时间 */
.deadline-container {
  display: flex;
  gap: 12px;
  align-items: center;
}

.deadline-picker {
  flex: 1;
}

.reminder-btn {
  white-space: nowrap;
}

/* 委托详情 */
.description-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.description-input {
  width: 100%;
}

.description-tools {
  display: flex;
  gap: 12px;
  align-items: center;
}

.upload-btn {
  white-space: nowrap;
}

/* 联系方式 */
.contact-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.contact-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.contact-icon {
  color: #667eea;
}

.contact-text {
  font-size: 14px;
  color: #666;
}

.change-contact-btn {
  white-space: nowrap;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 16px;
  justify-content: center;
  margin-top: 30px;
}

/* 提示信息 */
.publish-tips {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 20px;
  padding: 12px 16px;
  background: linear-gradient(135deg, #fff3cd 0%, #ffeaa7 100%);
  border-radius: 8px;
  border-left: 4px solid #ffc107;
}

.tips-icon {
  color: #ffc107;
  font-size: 16px;
}

.tips-text {
  font-size: 14px;
  color: #856404;
  font-weight: 500;
}

/* 增强输入框 */
.enhanced-input :deep(.el-input__wrapper) {
  border-radius: 8px;
  transition: all 0.3s ease;
}

.enhanced-input :deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #667eea;
}

.enhanced-input :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .entrust-publish {
    padding: 16px;
  }
  
  .publish-content {
    padding: 20px;
  }
  
  .category-selector {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .deadline-container {
    flex-direction: column;
    align-items: stretch;
  }
  
  .description-tools {
    flex-direction: column;
    align-items: stretch;
  }
}
</style> 